package lock

import "github.com/zeromicro/go-zero/core/stores/redis"

type TwoKeyLock struct {
	rds          *redis.Redis
	key1, key2   string
	lock1, lock2 *redis.RedisLock
}

func NewTwoKeyLock(rds *redis.Redis, key1, key2 string) *TwoKeyLock {
	return &TwoKeyLock{
		rds:   rds,
		key1:  key1,
		key2:  key2,
		lock1: redis.NewRedisLock(rds, key1),
		lock2: redis.NewRedisLock(rds, key2),
	}
}
func (b *TwoKeyLock) Lock() (bool, error) {
	ok1, err := b.lock1.Acquire()
	if err != nil {
		return false, err
	}
	if ok1 {
		ok2, err := b.lock2.Acquire()
		if err != nil {
			_, _ = b.lock1.Release()
			return false, err
		}
		if ok2 {
			return true, nil
		} else {
			_, _ = b.lock1.Release()
		}
	}
	return false, nil
}
func (b *TwoKeyLock) Unlock() error {
	_, err1 := b.lock1.Release()
	_, err2 := b.lock2.Release()
	if err1 != nil {
		return err1
	}
	if err2 != nil {
		return err2
	}
	return nil
}
